<?php

namespace App\Listeners;

use App\Common\RedisCache\YearActivityCache;
use App\Events\YearActivitySendCoupon;
use App\Models\LuckCouponLog;
use App\services\v1\ActivityServices;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Events\Dispatcher;
use Illuminate\Support\Facades\Log;

class YearActivitySendCouponSubscribe implements ShouldQueue
{
    public $queue        = 'YearActivitySendCouponSubscribe:{queue}';
    public $describetion = '发券订阅事件：';
    public function subscribe(Dispatcher $event)
    {
        $event->listen(
            'App\Events\YearActivitySendCoupon',
            'App\Listeners\YearActivitySendCouponSubscribe@sendCoupon'
        );
    }

    public function sendCoupon(YearActivitySendCoupon $yearActivitySendCoupon)
    {
        //获取抽奖券
        $activityService = new ActivityServices();
        $luckCoupons     = $activityService->getLuckCoupon();
        $day             = date('Ymd');
        //给登录用户发券
        $userId   = $yearActivitySendCoupon->data->id;
        $userName = $yearActivitySendCoupon->data->user_name;
        //限制同一用户一天领取一次
        $yearActivityCache = new YearActivityCache();
        $yearActivityCache->setKeyParameter([$day, $userId]);
        if ($yearActivityCache->get()) {
            Log::info($this->describetion.'用户{'.$userId.'}，'.$day.'已经发放抽奖券');
            return;
        }
        foreach ($luckCoupons as $luckCoupon) {
            $insertLuckLogData = [
                'user_id'   => $userId,
                'user_name' => $userName,
                'luck_id'   => $luckCoupon['id'],
                'luck_name' => $luckCoupon['name'],
                'number'    => $luckCoupon['number'],
                'activity_id'    => $luckCoupon['activity_id'],
                'get_time'  => date('Y-m-d H:i:s'),
            ];
            LuckCouponLog::create($insertLuckLogData);
        }
        $yearActivityCache->set(true, 86400);
    }
}